package com.atguigu.study.base;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncVSLockDemo {
    private final Lock lock=new ReentrantLock();
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName()+"\t"+"-----come in");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void m2(){
        if(lock.tryLock()){

            try {
                System.out.println(Thread.currentThread().getName()+"\t"+"-----come in");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
             lock.unlock();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+"\t"+"抢锁失败请重试");
        }
    }
    public void m3(){
        try {
            if(lock.tryLock(4L,TimeUnit.SECONDS)){

                try {
                    System.out.println(Thread.currentThread().getName()+"\t"+"-----come in");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            }else{
                System.out.println(Thread.currentThread().getName()+"\t"+"超过两秒抢锁失败请重试");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();
        new Thread(()-> syncVSLockDemo.m2(),"t1").start();
        new Thread(()-> syncVSLockDemo.m2(),"t2").start();
    }
}
